/*
 * Copyright (c) 2010-2011, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/effector/BorderRadiusFilter.h"
#include "alkes/core/Memory.h"
#include "alkes/media/LockImageBuffer.h"
#include "alkes/gfx/Renderer.h"
#include <math.h>

namespace alkes {

BorderRadiusFilter* BorderRadiusFilter::create(ImageBufferFactory* factory, int32_t radius)
{
    if (!factory)
        return 0;

    int32_t edge_num;
    EdgeInfo* edges = createEdgeInfo(radius, edge_num);
    if (!edges)
        return 0;

    return new BorderRadiusFilter(factory, radius, edges, edge_num);
}

void BorderRadiusFilter::destroy()
{
    delete this;
}

BorderRadiusFilter::BorderRadiusFilter(ImageBufferFactory* factory, int32_t radius, EdgeInfo* edges, int32_t edge_num)
: ImageFilter(factory)
, radius_(radius)
, edge_num_(edge_num)
, edges_(edges)
{
}

BorderRadiusFilter::~BorderRadiusFilter()
{
    if (edges_)
        destroyEdgeInfo(edges_);
}

bool BorderRadiusFilter::onApply(ImageBuffer* src, intrusive_ptr<ImageBuffer>* dst)
{
    uint16_t width, height;
    src->getImageSize(width, height);

    // invalid size.
    if (width / 2 < radius_ || height / 2 < radius_)
        return false;

    intrusive_ptr<ImageBuffer> temp(cloneImageBuffer(src));

    if (!temp)
        return false;

    LockImageBufferReadWrite write_lock(temp);

    if (0 == write_lock)
        return false;

    Renderer renderer(&write_lock);

    int32_t x;
    uint8_t current_y = edges_[0].y;
    int16_t sx = 0;
    int16_t uy = 0;
    int16_t by = 0;
    int16_t length = 0;
    Color color;
    for (x = 0; x < edge_num_; /*++x*/)
    {
        for (; current_y == edges_[x].y; ++x)
        {
            length = (int16_t)(radius_ - x);
            sx = width - length;
            uy = (int16_t)(radius_ - edges_[x].y);
            by = (int16_t)(height - (radius_ - edges_[x].y) - 1);

            --length;
            setPixel(renderer, color, UPoint2D(    sx, uy), x); // 45-90
            setPixel(renderer, color, UPoint2D(length, uy), x); // 90-135
            setPixel(renderer, color, UPoint2D(length, by), x); // 225-270
            setPixel(renderer, color, UPoint2D(    sx, by), x); // 270-315
        }
        current_y = edges_[x].y;

        if (0 < length)
        {
            renderer.drawLine(UPoint2D(sx+1, uy), length, Color::TRANS); // 45-90
            renderer.drawLine(UPoint2D(   0, uy), length, Color::TRANS); // 90-135
            renderer.drawLine(UPoint2D(   0, by), length, Color::TRANS); // 225-270
            renderer.drawLine(UPoint2D(sx+1, by), length, Color::TRANS); // 270-315
        }
    }

    for (x = 0; x < edge_num_; ++x)
    {
        length = (int16_t)(radius_ - edges_[x].y) + 1;
        sx = width - length;
        uy = (int16_t)(radius_ - x - 1);
        by = (int16_t)(height - (radius_ - x));

        --length;

        setPixel(renderer, color, UPoint2D(sx, uy), x);
        setPixel(renderer, color, UPoint2D(sx, by), x);
        setPixel(renderer, color, UPoint2D(length, uy), x);
        setPixel(renderer, color, UPoint2D(length, by), x);

        if (0 < length)
        {
            renderer.drawLine(UPoint2D(sx+1, uy), length, Color::TRANS); // 0-45
            renderer.drawLine(UPoint2D(sx+1, by), length, Color::TRANS); // 315-360
            renderer.drawLine(UPoint2D(   0, uy), length, Color::TRANS); // 135-180
            renderer.drawLine(UPoint2D(   0, by), length, Color::TRANS); // 180-225
        }
    }

    write_lock.detach();

    *dst = static_cast<ImageBuffer*>(temp);

    return true;
}

BorderRadiusFilter::EdgeInfo* BorderRadiusFilter::createEdgeInfo(int32_t radius, int32_t& edge_num)
{
    if (radius <= 0)
        return 0;

    EdgeInfo* edges = (EdgeInfo*)alkes_malloc(sizeof(EdgeInfo) * radius);
    if (!edges)
        return 0;

    int32_t x, y;
    float radius2 = (float)(radius * radius);
    int32_t limit = (int32_t)ceil(sqrt(radius2 / 2));
    float fy;

    if (limit == radius)
        limit = radius - 1;

    x = 0;
    while (x <= limit)
    {
        fy = sqrt(radius2 - x * x);
        y = (int32_t)(fy * 256) + 0xff;
        edges[x].y = (uint8_t)(y >> 8);
        edges[x].alpha = (uint8_t)(y & 0xff);
        ++x;
    }

    edge_num = x;
    return edges;
}

void BorderRadiusFilter::destroyEdgeInfo(EdgeInfo* edges)
{
    alkes_free(edges);
}

void BorderRadiusFilter::setPixel(Renderer& renderer, Color& color, const Point2D& pt, int32_t x)
{
    color = renderer.getPixel(pt);
    color.a = edges_[x].alpha;
    renderer.setPixel(pt, color);
}

}
